<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.gougucms.com
 */
namespace app\api\model;
use think\model;
use think\facade\Db;
use app\api\common\JwtToken;
class Article extends Model
{




    /**
     * 获取分页列表
     * @param $where
     * @param $param
     */
    public function getArticleList($where, $param)
    {
        $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
        $order = empty($param['order']) ? 'a.id desc' : $param['order'];
        $list = $this->where($where)
            ->field('a.id,a.title,a.cate_id,a.thumb,a.read,a.sort,a.create_time,c.id as cate_id,c.title as cate_title')
            ->alias('a')
            ->join('ArticleCate c', 'a.cate_id = c.id')
            ->order($order)
            ->paginate($rows, false, ['query' => $param])->each(function ($item, $key) {
                $item['thumb'] = 'https://'.$_SERVER['HTTP_HOST'].$item['thumb'];


            });;
        return $list;
    }





    /**
     * 根据id获取信息
     * @param $id
     */
    public function getArticleById($id,$token=null)
    {
        $info = $this->where('id', $id)->find();
        $uid=JwtToken::getUidByToken($token)??0;
        if($info && $uid){
            //判断此用户是否已阅读过此文章
            $has_read=ArticleReadLog::where(['uid'=>$uid,'article_id'=>$id])->whereNull('delete_time')->find();
            if(!$has_read){
                $arr=['article_id'=>$id,'uid'=>$uid,'create_time'=>time(),'update_time'=>time()];
                ArticleReadLog::insert($arr);
                $info->save(['read'=>$info->read+1]);
            }
        }
        return $info;
    }



}

